;; solutions to Guided Practice 6.1: pizza problem ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; QUESTION 1 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (define-struct plain-pizza ()) (define-struct topped-pizza (topping base)) ;; A Topping is a String. ;; A Pizza is either ;; -- (make-plain-pizza) ;; -- (make-topped-pizza Topping Pizza) ;; INTERP: ;; (make-plain-pizza) represents a pizza with no toppings ;; (make-topped-pizza t p) represents the pizza p with topping t added ;; on top. ;; replace-all-anchovies-with-onions ;; : Pizza -> Pizza ;; RETURNS: a pizza like the given pizza, but with ;; anchovies in place of each layer of onions ;; STRATEGY: Use template for Pizza on p (define (replace-all-anchovies-with-onions p) (cond [(plain-pizza? p) empty] [else (if (string=? (topped-pizza-topping p) "anchovies") (make-topped-pizza "onions" (replace-all-anchovies-with-onions (topped-pizza-base p))) (make-topped-pizza (topped-pizza-topping p) (replace-all-anchovies-with-onions (topped-pizza-base p))))])) ;; replace-all-anchovies : Pizza Topping -> Pizza ;; RETURNS: a pizza like the given pizza, but with ;; all anchovies replaced by the given topping. ;; STRATEGY: Use template for Pizza on p (define (replace-all-anchovies p replacement) (cond [(plain-pizza? p) empty] [else (if (string=? (topped-pizza-topping p) "anchovies") (make-topped-pizza replacement (replace-all-anchovies (topped-pizza-base p) replacement)) (make-topped-pizza (topped-pizza-topping p) (replace-all-anchovies (topped-pizza-base p) replacement)))])) ;; replace-topping : Pizza Topping Topping -> Pizza ;; RETURNS: a pizza like the given one, but with ;; all instances of the first topping replaced by ;; the second one. ;; STRATEGY: Use template for Pizza on p (define (replace-topping p topping replacement) (cond [(plain-pizza? p) empty] [else (if (string=? (topped-pizza-topping p) topping) (make-topped-pizza replacement (replace-topping (topped-pizza-base p) topping replacement)) (make-topped-pizza (topped-pizza-topping p) (replace-topping (topped-pizza-base p) topping replacement)))])) ;; another solution (also Use template for Pizza on p): (define (replace-topping p topping replacement) (cond [(plain-pizza? p) empty] [else (make-topped-pizza (if (string=? (topped-pizza-topping p) topping) replacement (topped-pizza-topping p)) (replace-topping (topped-pizza-base p) topping replacement))]))